<template>
    <div id="regist">
        <el-card>
            <div slot="header">
                <img src="/static/logo.png" alt=""><strong>问卷系统注册</strong>
            </div>
            <el-form ref="refRegist" status-icon :model="formRegist" :rules="rules" label-width="80px" label-position="left">
                <!-- prop对应rules里的对象 -->
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="formRegist.username"></el-input>
                </el-form-item>
                <el-form-item label="密 码" prop="password">
                    <el-input type="password" v-model="formRegist.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="passwordConfirm">
                    <el-input type="password" v-model="formRegist.passwordConfirm"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="phone">
                    <el-input type="number" v-model="formRegist.phone"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input type="email" v-model="formRegist.email"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="formRegist.gender">
                        <el-radio label="m">男</el-radio>
                        <el-radio label="f">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm()">注册</el-button>
                    <el-button @click="resetForm('refRegist')">重置</el-button>
                    <el-button @click="$router.push('/login')">返回</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
  export default {
    data() {
      //第一个密码验证
      let passwordReg = /^(?![^a-zA-Z]+$)(?!\D+$).{6,15}$/;
      let validatePassword = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("密码不能为空!"));
        }
        setTimeout(() => {
          if (!passwordReg.test(value)) {
            callback(new Error("6-18位数字与字母组合"));
          } else {
            callback();
          }
        }, 1000);
      };
      //确认密码验证
      let validatePass2 = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.formRegist.password) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      return {
        formRegist: {
          username: "",
          password: "",
          passwordConfirm: "",
          phone: "",
          email: "",
          gender: ""
        },
        rules: {
          password: [{
            required: true,
            validator: validatePassword,
            trigger: "blur"
          }],
          passwordConfirm: [{
            required: true,
            validator: validatePass2,
            trigger: "blur"
          }],
          gender: [{
            required: true,
            message: "请选择性别",
            trigger: "change"
          }],
          username: [{
            required: true,
            validator: (rule, value, callback) => {
              if (!/^.{4,8}$/.test(value)) {
                callback(new Error('用户名为4-8个字段'));
                return;
              }
              this.axios.get(`/users/exists/username/${value}`).then((res) => {
                if (res.data == false) {
                  callback()
                } else {
                  callback(new Error('用户名不能重复'))
                }
              }).catch()
            },
            trigger: 'blur'
          }],
          phone: [{
            required: true,
            validator: (rule, value, callback) => {
              if (!/^1[34578]\d{9}$/.test(value)) {
                callback(new Error('手机号11位数字'));
                return;
              }
              this.axios.get(`/users/exists/phone/${value}`).then((res) => {
                if (res.data == false) {
                  callback()
                } else {
                  callback(new Error('手机号不能重复'))
                }
              }).catch()
            },
            trigger: 'blur'
          }],
          email: [{
            required: true,
            validator: (rule, value, callback) => {
              if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(value)) {
                callback(new Error('邮箱格式不正确'));
                return;
              }
              this.axios.get(`/users/exists/email/${value}`).then((res) => {
                if (res.data == false) {
                  callback()
                } else {
                  callback(new Error('邮箱不能重复'))
                }
              }).catch()
            },
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      submitForm() {
        //this.$refs指组件里的ref
        this.$refs.refRegist.validate(flag => {
          if (flag) {
            this.axios
              .post("/users/regist", this.formRegist)
              .then(res => {
                this.$message.success("注册成功");
                this.store("logged", true);
                this.store("loggedInfo", res.data);
                //  注册成功后再次调用登录请求，把登录需要的参数username和password传过去，请求成功后再跳转到index页面
                if (this.store("loggedInfo")) {
                  this.axios
                    .post("/users/login", {
                      username: this.store('loggedInfo').username,
                      password: this.store('loggedInfo').password
                    }).then(res => {
                      this.$router.push("/index");
                    });
                }
              })
              .catch(() => {
                this.$message.error("注册失败");
              });
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    },
    created() {
      if (this.store("logged")) {
        this.$router.push("/index");
      }
    }
  }
</script>

<style>
  #header {
    text-align: center;
  }
  #regist {
    width: 400px;
    margin: 20px auto;
  }
  .registTitle {
    text-align: center;
  }
</style>
